package server;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.zip.InflaterInputStream;

public class Interpreter {
	ArrayList<String> debugList = new ArrayList<String>();
	int currentLine = 0;
	int headerLine = 0;

	int dataLineStart = 0;

	Boolean headersFinished = false;
	byte[] data;
	public Interpreter(){
	}

	public void write(byte[] reply) throws IOException{
		String value = new String(reply);
		debugList.add(value);
		System.out.println("[Header] - " + value);
	}

	public void writeLine(String replyLine) throws IOException{		
		debugList.add(replyLine);
		if(!headersFinished){
			if(headerLine == 0){
				System.out.println("[Headers] - " + replyLine);
			} else {
				System.out.println("            " + replyLine);
			}
			headerLine++;
			if(replyLine.equals("")){
				headersFinished = true;
				dataLineStart = headerLine;
			}
		} else {
			readData(replyLine);
		}
		currentLine++;

	}

	public void readData(String string){
		if(currentLine == dataLineStart){
			data = string.getBytes();
			System.out.println("[Data] - " + string);
		} else {
			data = concatenateByteArrays(data, string.getBytes());
			System.out.println("         " + string);
		}
		
		byte[] newArray = new byte[data.length - 4];
		System.arraycopy(data, 4, newArray, 0, newArray.length);
		
	}

	byte[] concatenateByteArrays(byte[] a, byte[] b) {
	    byte[] result = new byte[a.length + b.length]; 
	    System.arraycopy(a, 0, result, 0, a.length); 
	    System.arraycopy(b, 0, result, a.length, b.length); 
	    return result;
	} 
	
	public void decompress(byte[] reply) throws IOException{
		InputStream in = new InflaterInputStream(new ByteArrayInputStream(reply));
		byte[] buffer = new byte[1000];
		int len;
		ArrayList<String> debugList = new ArrayList<String>();
		while((len = in.read(buffer)) > 0) {
			String value = new String(buffer);
			System.out.println("[Decompressed] - " + value);

		}
		in.close();
	}
}
